package com.sean.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sean.common.constant.ProductConstant;
import com.sean.common.utils.PageUtils;
import com.sean.common.utils.Query;
import com.sean.common.utils.R;
import com.sean.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.sean.gulimall.product.dao.AttrGroupDao;
import com.sean.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.sean.gulimall.product.entity.AttrEntity;
import com.sean.gulimall.product.entity.AttrGroupEntity;
import com.sean.gulimall.product.service.AttrAttrgroupRelationService;
import com.sean.gulimall.product.service.AttrGroupService;
import com.sean.gulimall.product.service.AttrService;
import com.sean.gulimall.product.service.CategoryService;
import com.sean.gulimall.product.vo.AttrGroupWithAttrsVo;
import com.sean.gulimall.product.vo.AttrRelationVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrAttrgroupRelationService attrgroupRelationService;
    @Autowired
    private AttrService attrService;
    @Resource
    private AttrAttrgroupRelationDao attrgroupRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCategoryId(Map<String, Object> params, Long categoryId) {
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        IPage<AttrGroupEntity> page = null;
        //如果categoryId=0则查询所有的属性分组
        if(categoryId == 0)
        {
            page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    new QueryWrapper<AttrGroupEntity>()
            );
        }else{
            Object key = params.get("key");
            wrapper.lambda().eq(AttrGroupEntity::getCatelogId,categoryId);
            if(key != null )
            {
                wrapper.and((obj)->{
                    obj.like("attr_group_id",key).or().like("attr_group_name",key);
                });
            }
            page = this.page(new Query<AttrGroupEntity>().getPage(params),wrapper);
        }
        //设置商品分类名称
        page.getRecords().stream().forEach(attrGroup->{
            attrGroup.setCatelogName(categoryService.getById(attrGroup.getCatelogId()).getName());
        });
        return new PageUtils(page);
    }

    @Override
    public R queryAllAttrByAttrGroupId(Long attrGroupId) {
        AttrGroupEntity attrGroupEntity = this.getById(attrGroupId);
        if(attrGroupEntity == null)
        {
            return R.error("该属性分组不存在");
        }
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AttrAttrgroupRelationEntity::getAttrGroupId,attrGroupId);
        //获取该属性分组下所有的属性id
        List<Long> attrIdList = attrgroupRelationService.list(queryWrapper).stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        List<AttrEntity> attrEntityList = new ArrayList<>();
        if(!attrIdList.isEmpty())
        {
            attrEntityList =  attrService.listByIds(attrIdList);
        }

        return R.ok().put("data",attrEntityList);
    }

    @Override
    public R removeRelation(AttrRelationVo[] attrRelationArray) {
        List<AttrAttrgroupRelationEntity> relationEntityList = Arrays.asList(attrRelationArray).stream().map((attrRelationVo) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attrRelationVo, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        if(relationEntityList.isEmpty())
        {
            return R.error("请选择要删除的属性关联关系");
        }
        //批量删除关联关系
        attrgroupRelationDao.attrRelationRemoveBatch(relationEntityList);
        return R.ok();
    }

    @Override
    public R queryAllAttrNoRelationByAttrGroupId(Map<String, Object> params,Long attrGroupId) {
        AttrGroupEntity attrGroupEntity = this.getById(attrGroupId);
        if(attrGroupEntity == null)
        {
            return R.error("该属性分组不存在");
        }
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        //获取所有的关联分组的基本属性id
        List<Long> attrIdList = attrgroupRelationService.list(queryWrapper).stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        IPage<AttrEntity> page = new Page<>();
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        //产品分类id
        wrapper.lambda()
                .eq(AttrEntity::getCatelogId,attrGroupEntity.getCatelogId())
                .eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        if(!attrIdList.isEmpty())
        {
            wrapper.lambda().notIn(AttrEntity::getAttrId,attrIdList);
        }
        //关键字查询：对属性id查询或对属性名进行模糊查询
        Object key = params.get("key");
        if(key != null)
        {
            wrapper.lambda().and(w->{
                w.eq(AttrEntity::getAttrId,key).or().like(AttrEntity::getAttrName,key);
            });
        }

        page = attrService.page(new Query<AttrEntity>().getPage(params), wrapper);
        return R.ok().put("page",new PageUtils(page));
    }

    @Override
    public R addRelation(AttrRelationVo[] attrRelationArray) {
        List<AttrAttrgroupRelationEntity> relationEntityList = Arrays.asList(attrRelationArray).stream().map((attrRelationVo) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attrRelationVo, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        attrgroupRelationService.saveBatch(relationEntityList);
        return R.ok();
    }

    @Override
    public R getAttrGroupWithAttrsByCatelogId(Long categoryId) {

        if(Objects.isNull(categoryId))
        {
            return R.error("商品Id不能为空");
        }
        //1.根据商品分类id查询出该商品所有的属性分组
        List<AttrGroupEntity> attrGroupList = this.list(new LambdaQueryWrapper<AttrGroupEntity>().eq(AttrGroupEntity::getCatelogId, categoryId));
        //2.根据商品分组id查询出该分组下的所有属性
        List<AttrGroupWithAttrsVo> data = attrGroupList.stream().map(attrGroup -> {
            AttrGroupWithAttrsVo attrGroupWithAttrsVo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(attrGroup, attrGroupWithAttrsVo);

            List<AttrEntity> attrEntities = attrService.getRelationAttr(attrGroup.getAttrGroupId());
            attrGroupWithAttrsVo.setAttrs(attrEntities);
            return attrGroupWithAttrsVo;
        }).collect(Collectors.toList());

        return R.ok().put("data",data);
    }
}